package com.study.springboot.controller;


import com.study.springboot.common.config.MyAnnotation;
import com.study.springboot.common.constant.ErrorRespStatusEnum;
import com.study.springboot.common.mvc.BaseController;
import com.study.springboot.common.mvc.CustomedException;
import com.study.springboot.common.mvc.RespData;
import com.study.springboot.service.MultipleEnvironmentsService;
import com.study.springboot.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Admin
 * @since 2021-11-21
 */
@RestController
@RequestMapping("/test")
public class TestController extends BaseController {

    @Autowired
    MultipleEnvironmentsService multipleEnvironmentsService;

    @Autowired
    TestService testService;

    /* 测试日期格式转换 */
    @PostMapping("/dateConvert")
    public RespData testDateConvert(@RequestParam("date") Date date) {
        return success(date);
    }

    /* 测试异常处理器 */
    @GetMapping("/exceptionHandler")
    public RespData testExceptionHandler() {
        if (true) {
            throw new CustomedException(ErrorRespStatusEnum.UNAUTHORIZED);
        }
        return success();
    }

    /* 测试多环境 */
    @GetMapping("/multipleEnvironments")
    public String testMultipleEnvironments() {
        return multipleEnvironmentsService.testMultipleEnvironments();
    }

    /* 测试读取配置文件 */
    @GetMapping("/readProfiles")
    public void testReadProfiles() {
        testService.testReadProfiles();
    }

    /* 测试事务 */
    @GetMapping("/testTransaction")
    public void testTransaction() {
        testService.testTransaction();
    }

    /* 测试注解标注的Aop*/
    @MyAnnotation("哈哈哈")
    @GetMapping("/aop")
    public void aop() {
    }

    /* 测试下载模板文件*/
    @GetMapping("/downloadTemplate")
    public RespData downloadTemplate(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=TermsAndConditions.pdf");
        ServletOutputStream os = null;
        InputStream is = null;
        try {
            os = response.getOutputStream();
            is = this.getClass().getClassLoader().getResourceAsStream("/static/TermsAndConditions.pdf");
            FileCopyUtils.copy(is, os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            os.close();
            is.close();
        }
        return success();
    }


}

